using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using FServer.Infrastructure.Data;
using FServer.Infrastructure.Services;

namespace FServer.Infrastructure.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
    {
        // 添加数据库上下文
        services.AddDbContext<GameDbContext>(options =>
        {
            options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"), npgsqlOptions =>
            {
                npgsqlOptions.EnableRetryOnFailure(3);
                npgsqlOptions.CommandTimeout(30);
            });
            
            options.EnableSensitiveDataLogging(false);
            options.EnableServiceProviderCaching();
            options.EnableDetailedErrors(false);
        });

        // 添加 Redis 缓存
        services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = configuration.GetConnectionString("Redis");
            options.InstanceName = "FServer";
        });

        // 添加健康检查
        services.AddHealthChecks()
            .AddDbContext<GameDbContext>()
            .AddRedis(configuration.GetConnectionString("Redis"));

        // 注册服务
        services.AddScoped<ICacheService, RedisCacheService>();
        services.AddScoped<IMessageQueueService, RabbitMQService>();
        services.AddScoped<IVersionService, VersionService>();
        services.AddScoped<IGameServerService, GameServerService>();

        return services;
    }
}
